
<style lang="scss">
.page-editor {
  [data-set=question] {
    //display: block;
    color: var(--el-color-danger)
  }
}
</style>

<template>
  <div class="page-editor">
    <div>
      <el-button @click="insertText">插入</el-button>
    </div>
    <div style="border: 1px solid #ccc;">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="html"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="onCreated"
          @onChange="onChange"
      />
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { SlateTransforms } from '@wangeditor/editor'


let toolbarKeys = [
  '|',
  'undo',
  'redo',
  '|',
  // 'header1',
  // 'header2',
  // 'header3',
  // 'blockquote',
  // '|',
  'bold',
  'underline',
  'italic',
  'color',
  'bgColor',
  '|',
  'fontSize',
  'fontFamily',
  'lineHeight',
  // 'codeSelectLang',
  'divider',
    'clearStyle'
  // 'deleteTable',
]

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {
        toolbarKeys
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onChange(editor) {
      // console.log('onChange', editor)
    },
    insertText() {
      setTimeout(() => {
        // this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
        // console.log(this.editor)
        let editor = this.editor

        // console.log(editor, editor.getText())

        if (editor.children && editor.children.length === 1 && editor.getText() === '') {
          SlateTransforms.removeNodes(editor)
        }
        // editor.focus()
        // SlateTransforms.removeNodes(editor)
        // const node1 = { type: 'question', children: [{ text: 'aaa'}] }
        const node1 = { type: 'paragraph', children: [{ text: 'aaa', color: 'red'}] }
        // // const node2 = { type: 'paragraph', children: [{ text: 'bbb' }] }
        const nodeList = [node1]
        SlateTransforms.insertNodes(editor, nodeList)

        // editor.insertBreak()
      }, 30)
    }
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>

